<template>
  <div class="wrap" :class="!callScreen ? 'business-history-table' : ''">
    <affix :label="title">
      <el-row>
        <el-col class="history-business-num" :span="24">
          {{ $t('business.countRecord', { count: tableData.count }) }}
        </el-col>
      </el-row>
      <time-line :items="tableData.list" timeKey="createTime">
        <el-row class="history-wrap" slot="item" slot-scope="props">
          <el-col :span="8">
            <el-tooltip
              :open-delay="150"
              placement="right"
              popper-class="business-history-wap"
              :visibleArrow="false"
              effect="light"
              transition="fade-leave"
            >
              <div
                slot="content"
                class="card-detail"
                v-loading="toolTipLoad"
                element-loading-background="rgba(0, 0, 0, 0)"
              >
                <div class="card-detail-tittle" v-show="!toolTipLoad">{{ $t('business.businessContent') }}</div>
                <table>
                  <tbody valign="top">
                    <template v-for="(i, index) in toolTipObj[props.item._id] || []">
                      <tr class="card-detail-item">
                        <td class="data-name">{{ i.name }}</td>
                        <td class="break-all">{{ i.value }}</td>
                      </tr>
                    </template>
                  </tbody>
                </table>
              </div>
              <div
                @click.stop="businessDetail(props.item._id)"
                class="history-title"
                @mouseenter="mouseenterToolTip(props.item._id)"
              >
                <span class="font14">{{ props.item.businessTypeName }}</span>
                <span class="history-title-detail" m7automation="details">{{
                  $t('intelligentQualityCheck.intelDetails')
                }}</span>
              </div>
            </el-tooltip>
            <div v-if="props.item.number" class="number">(ID:{{ props.item.number }})</div>
            <div class="state process" v-if="!props.item.dispose">{{ $t('business.dealing') }}</div>
            <div class="state finish" v-else>{{ $t('business.complete') }}</div>
          </el-col>
          <el-col :span="16">
            <div class="history-content">
              <div class="left">
                <p class="business-name">{{ $t('business.createBusiness') }}</p>
                <p class="agent">{{ props.item.agentName }}</p>
                <p>{{ props.item.createTime }}</p>
              </div>
              <div class="center">
                <div class="business-name arrow-icon">
                  <span v-for="i in 20" class="dot"></span>
                  <span class="arrow"></span>
                </div>
              </div>
              <div class="right">
                <p class="business-name">{{ props.item.disposeDisplay }}</p>
                <p class="agent">{{ props.item.masterName ? props.item.masterName : '----' }}&nbsp;</p>
                <p>{{ props.item.lastUpdateTime }}</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </time-line>
      <el-row>
        <el-col :span="24" class="next-page" v-if="isLoadMoreShow">
          <div class="btn" @click.stop="loadMore">{{ $t('public.loadMore') }}</div>
        </el-col>
      </el-row>
    </affix>
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      :title="$t('business.businessHistoryDetail')"
      :visible.sync="detailShow"
      :width="callScreen ? '70%' : '800px'"
      :modal="callScreen ? false : true"
      @close="off"
    >
      <!-- webpack -->
      <business class="business-dialog" :busId="busId" :showHistory="true" v-if="detailShow" v-on:event="businessEvent" :callScreen="true" :relatedBusinessShow="false"></business>
      <!-- webpack end -->
    </el-dialog>
  </div>
</template>
<script>
import affix from '../../ui-modules/affix/Affix.vue'
import TimeLine from '../../ui-modules/affix/TimeLine'
// webpack
import business from '@/components/public-modules/cust-tab-content/business/index.vue'
import { sortBusinessFields, getStartStep } from '@/utils/workflowUtils'
export default {
  name: 'BusinessHistoryTable',
  data() {
    return {
      toolTipLoad: false,
      toolTipObj: {},
      isLoadMoreShow: false,
      data: {
        customer: this.cid,
        type: 'business',
        page: 1,
        limit: 20
      },
      tableData: {
        count: 0,
        list: []
      },
      loading: true,
      busId: '',
      detailShow: false,
      currToolTipId: '',
      newBusinessNumbers: this.businessNumbers
    }
  },
  props: {
    cid: String,
    callScreen: Boolean,
    title: String,
    type: String,
    // 工单编号
    businessNumbers: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    refreshHistoryTable() {
      return this.$store.state.business.transCache.refreshCustomerBusinessHistory
    }
  },
  watch: {
    refreshHistoryTable() {
      if (this.refreshHistoryTable.customer === this.cid && this.loading) {
        this.data.page = 1
        this.tableData.list = []
        this.loading = false
        this.fetchData()
      }
    },
    businessNumbers(newVal, oldVal) {
      this.newBusinessNumbers = newVal
      this.fetchData()
    }
  },
  components: {
    affix,
    // webpack
    business,
    TimeLine
  },
  methods: {
    businessType(item) {
      let businessFlows = this.$getCache('businessFlow') || []
      for (let i = 0; i < businessFlows.length; i++) {
        if (businessFlows[i]._id === item.flow) {
          let { fields } = businessFlows[i]
          let step = getStartStep(businessFlows[i])
          let stepFields = step.stepFields || []
          let detail = [{ name: this.$t('business.businessNumber'), value: item.number }]
          sortBusinessFields(stepFields, fields, item, detail, 'card')
          return detail
        }
      }
      return []
    },
    loadMore() {
      this.data.page++
      this.fetchData()
    },
    businessEvent(eventData) {
      if (eventData.event !== 'changeBusinessMaster') {
        this.$store.dispatch('getBusinessDetailById', { _id: this.busId })
      }
      this.$store.commit('business/REFRESH_CUSTOMER_BUSINESS_HISTORY', this.cid)
    },
    fetchData() {
      this.data.customer = this.cid
      // 关联工单
      if (this.type === 'related') {
        let data = { number: { $in: this.newBusinessNumbers } }
        this.$store.dispatch('queryAllBusiness', data).then((res) => {
          if (res && res.success) {
            if (res.list.length === 0) {
              this.tableData.list = []
              this.tableData.count = 0
            } else {
              const getListItemById = (list, id) => {
                for (let i = 0; i < list.length; i++) {
                  if (list[i]._id === id) {
                    return list[i]
                  }
                }
              }
              Promise.all([
                this.$store.dispatch('getCache', { type: 'agents' }),
                this.$store.dispatch('getCache', { type: 'businessFlow' }),
                this.$store.dispatch('getCache', { type: 'businessFlowStep' })
              ]).then(([agents, businessFlows, businessFlowSteps]) => {
                res.list.forEach((item) => {
                  // 创建人
                  let agentObj = getListItemById(agents, item.createUser || '')
                  let agentName = agentObj ? (agentObj.displayName ? agentObj.displayName + agentObj.exten : '') : ''
                  item.agentName = agentName
                  // 当前工单
                  let businessTypeName = ''
                  let businessFlow = getListItemById(businessFlows, item.flow)
                  businessTypeName = businessFlow ? (businessFlow.name ? businessFlow.name : '') : ''
                  item.businessTypeName = businessTypeName
                  // 当前步骤
                  let disposeDisplay = ''
                  let businessStep = getListItemById(businessFlowSteps, item.step)
                  disposeDisplay = businessStep ? (businessStep.name ? businessStep.name : '') : ''
                  item.disposeDisplay = disposeDisplay
                  if (businessStep && businessStep.type === 'sys') {
                    item.dispose = businessStep.systemFn
                  }
                })
                this.tableData.list = res.list
                this.tableData.count = res.list.length
              })
            }
          }
        })
      } else {
        // 工单历史
        this.$store.dispatch('queryCustomerBusinessHistory', this.data).then((val) => {
          this.tableData.count = val.count
          if (val.list.length < 20) {
            this.isLoadMoreShow = false
          } else {
            this.isLoadMoreShow = true
          }
          this.tableData.list = this.tableData.list.concat(val.list)
          this.loading = true
        })
      }
    },
    mouseenterToolTip(id) {
      console.log(id)
      console.log(this.toolTipObj)
      // store里有，直接从store 里取，否则发请求取
      if (!this.$store.state.business['current'].businessAction[id]) {
        this.toolTipLoad = true
        this.$store
          .dispatch('getBusinessDetailById', { _id: id, hiddenLoad: true })
          .then((res) => {
            if (res) {
              console.log('success')
              this.toolTipLoad = false
              this.currToolTipId = id
              let _item = this.$store.state.business['current'].businessAction[id]
              this.$set(this.toolTipObj, id, this.businessType(_item))
              console.log(this.toolTipObj)
            } else {
              console.log('error')
            }
          })
          .catch(() => {
            console.log('catch')
          })
      } else {
        this.toolTipLoad = false
        let _item = this.$store.state.business['current'].businessAction[id]
        this.$set(this.toolTipObj, id, this.businessType(_item))
      }
    },
    businessDetail(id) {
      this.$store
        .dispatch('getBusinessDetailById', { _id: id })
        .then((res) => {
          if (res) {
            this.detailShow = true
            this.busId = id
          } else {
            this.detailShow = false
          }
        })
        .catch(() => {
          this.detailShow = false
        })
    },
    off() {
      this.detailShow = false
    }
  },
  beforeMount() {
    this.data.page = 1
    this.tableData.list = []
    this.fetchData()
  }
}
</script>
<style lang="stylus" scoped>
@import "../../../assets/common.styl"
.wrap
  padding 15px 0 0
.history-business-num
  font-size 12px
  color $cf-gray4
  padding-bottom 26px
.history-title
  display inline-flex
  color $cf-gray2
  font-weight bold
  &:hover
    color $c-main
    cursor pointer
  .history-title-detail
    color $c-main
    padding-left 9px
    font-size 12px
.history-wrap
  padding 12px 10px
  border-radius 5px
.number
  color $cf-gray4
.state
  padding-top 5px
  font-size 14px
.finish
  color $cf-gray6
.process
  color $cf-color2
.history-content
  float right
  display flex
  justify-content flex-start
  p
    color $cf-gray4
    font-size 12px
    padding-bottom 1px
    max-width 130px
  .business-name
    font-size 14px
    color $cf-gray4
    padding-bottom 6px
.btn
  display inline-block
  padding-left 20px
  margin-left 167px
  font-size 12px
  cursor pointer
  color $c-main
.arrow-icon
  width 175px
  display flex
  margin-top 6px
  justify-content space-between
  padding-right 10px
  span
    display block
  .dot
    width 4px
    height 4px
    border-radius 2px
    background #9b9b9b
  .arrow
    margin-top -3px
    width 6px
    height 6px
    border-top 2px solid #9b9b9b
    border-right 2px solid #9b9b9b
    transform rotate(45deg)
.card-detail
  min-height 30px
  .card-detail-tittle
    color $cf-gray2
    font-weight bold
    padding-bottom 10px
  .card-detail-item
    line-height 22px
  .data-name
    color $cf-gray4
    min-width 50px
    width 50px
    padding-right 24px
  .break-all
    color $cf-gray2
    word-break break-all
    white-space pre-line
  .data-padding
    padding-top 15px
</style>
